package com.ch.engine.daily;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.StopWatch;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

public class BrandDuplicateChecker {

    public static List<DuplicateBrandDTO> findDuplicateBrands(List<String> brands, List<String> brandsInDb) {
        if (CollUtil.isEmpty(brands) || CollUtil.isEmpty(brandsInDb)) {
            return CollUtil.newArrayList();
        }
        List<DuplicateBrandDTO> result = new ArrayList<>();
        for (String brand : brands) {
            List<String> duplicates = new ArrayList<>();
            for (String existingBrand : brandsInDb) {
                if (hasRepeatedSubstring(brand, existingBrand)) {
                    duplicates.add(existingBrand);
                }
            }
            if (!duplicates.isEmpty()) {
                DuplicateBrandDTO dto = new DuplicateBrandDTO();
                dto.setBrand(brand);
                dto.setDuplicateBrands(duplicates);
                result.add(dto);
            }
        }
        return result;
    }

    public static boolean hasRepeatedSubstring(String str1, String str2) {
        if (StringUtils.isBlank(str1) || StringUtils.isBlank(str2)) {
            return false;
        }
        str1 = str1.toLowerCase();
        str2 = str2.toLowerCase();
        // 设定最小匹配长度
        int minLen = Math.min(4, str1.length());
        HashSet<String> substrings = new HashSet<>();
        // 存储 str1 的所有长度为 minLen 的子串
        for (int i = 0; i <= str1.length() - minLen; i++) {
            substrings.add(str1.substring(i, i + minLen));
        }
        // 检查 str2 是否包含相同的子串
        for (int i = 0; i <= str2.length() - minLen; i++) {
            if (substrings.contains(str2.substring(i, i + minLen))) {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        List<String> totalBrands = new ArrayList<>();
        List<String> brands = new ArrayList<>();

//        for (int i = 1; i <= 10; i++) {
//            brands.add(UUID.randomUUID().toString().substring(0, 10));
//        }
//
//        for (int i = 1; i <= 2000; i++) {
//            totalBrands.add(UUID.randomUUID().toString());
//        }

        brands.add("as d");
        totalBrands.add("Asd");

        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        System.out.println(JSONObject.toJSONString(findDuplicateBrands(brands, totalBrands)));
        stopWatch.stop();
        System.out.println(stopWatch.getLastTaskTimeMillis());
    }
}
